<template>
	<view class="content">
			
        <view class="DrawerPage content" :class="modalName=='viewModal'?'show':''">
        			
        
		<view class="cu-bar search bg-gradual-blue">
			<view class="cu-avatar round"  @tap="showModal" data-target="viewModal"><text  class="lg text-gray cuIcon-more" ></text></view>
			<view class="search-form round">
				<text class="cuIcon-search"></text>
				<input @confirm="search" @input="textInput"  :adjust-position="false" type="text" placeholder="搜索今日热门" confirm-type="search"></input>
			</view>
			<view class="action">
				
			</view>
		</view>
		
		<!-- 顶部选项卡 -->
		<scroll-view id="nav-bar" class="nav-bar" scroll-x scroll-with-animation :scroll-left="scrollLeft">
			<view 
				v-for="(item,index) in tabBars" :key="item.id"
				class="nav-item"
				:class="{current: index === tabCurrentIndex}"
				:id="'tab'+index"
				@click="changeTab(index)"
			>{{item.name}}</view>
		</scroll-view>
		
		<!-- 下拉刷新组件 -->
		<mix-pulldown-refresh ref="mixPulldownRefresh" class="panel-content"  :top="90" @refresh="onPulldownReresh" @setEnableScroll="setEnableScroll">
			<!-- 内容部分 -->
			<swiper 
				id="swiper"
				class="swiper-box" 
				:duration="300" 
				:current="tabCurrentIndex" 
				@change="changeTab"
			>
				<swiper-item v-for="tabItem in tabBars" :key="tabItem.id">
					<scroll-view 
						class="panel-scroll-box" 
						:scroll-y="enableScroll" 
						@scrolltolower="loadMore"
						>
						<!-- 
							* 新闻列表 
							* 和nvue的区别只是需要把uni标签转为weex标签而已
							* class 和 style的绑定限制了一些语法，其他并没有不同
						-->
						<view class="cu-card article"  v-for="(item, index) in tabItem.newsList" :key="index" @click="navToDetails(item)">
							<view class="cu-item shadow">
								<view class="title"><view class="text-cut">{{item.Title}}</view></view>
								<view class="content">
									<image v-if="item.imgUrl" :src="item.imgUrl"
									 mode="aspectFill"></image>
									<view class="desc">
										<view class="text-content"> {{item.Title}}</view>
										<view>
											<view v-if="item.hotDesc" class="cu-tag bg-red light sm round">{{item.hotDesc}}</view>
										
										</view>
									</view>
								</view>
							</view>
						</view>
						
						<!-- 上滑加载更多组件 -->
						<mix-load-more :status="tabItem.loadMoreStatus"></mix-load-more>
					</scroll-view>
				</swiper-item>
			</swiper>
		</mix-pulldown-refresh>
	</view>
	<view class="DrawerClose " :class="modalName=='viewModal'?'show':''" @tap="hideModal">
		<text class="cuIcon-pullright"></text>
	</view>
	<scroll-view scroll-y class="DrawerWindow" :class="modalName=='viewModal'?'show':''">
		<view class="cu-list menu card-menu margin-top-xl margin-bottom-xl shadow-lg">
			<view class="cu-item arrow" v-for="(item,index) in leftlist" :key="index" @tap="tapType(item)">
				<view class="content">
					<text class="text-grey" :class="'cuIcon-'+icon[index]"></text>
					<text class="text-grey">{{item}}</text>
				</view>
			</view>
			<view class="cu-item arrow" @tap="tapRss">
				<view class="content">
					<text class="cuIcon-settings text-grey"></text>
					<text class="text-grey">RSS</text>
				</view>
			</view>
		</view>
	</scroll-view>
	</view>
</template>

<script>
	import mixAdvert from '@/components/mix-advert/vue/mix-advert';
	import mixPulldownRefresh from '@/components/mix-pulldown-refresh/mix-pulldown-refresh';
	import mixLoadMore from '@/components/mix-load-more/mix-load-more';
	let windowWidth = 0, scrollTimer = false, tabBar;
	export default {
		components: {
			mixPulldownRefresh,
			mixLoadMore,
			mixAdvert
		},
		data() {
			return {
				content: null,
				tabCurrentIndex: 0, //当前选项卡索引
				scrollLeft: 0, //顶部选项卡左滑距离
				enableScroll: true,
				tabBars: [],
				modalName:null,
				curTab:'综合',
				leftlist:['IT','体育','全部','娱乐','沙雕图','游戏','社区','科技','综合','财经','购物'],
				icon:['github','footprint','new','emoji','attentionfill','game','home','phone','all','rechargefill','shop']
			
			}
		},
		computed: {
		
		},
		async onLoad() {
			// 获取屏幕宽度
			windowWidth = uni.getSystemInfoSync().windowWidth;
			this.loadTabbars();
		},
		onReady(){
			// #ifndef MP
			
			
			// #endif
		},
		methods: {
			textInput(e){
				
				this.content =e.detail.value
				
			},
			showModal(e) {
				this.modalName = e.currentTarget.dataset.target
			},
			hideModal(e) {
				this.modalName = null
			},
			/**
			 * 数据处理方法在vue和nvue中通用，可以直接用mixin混合
			 * 这里直接写的
			 * mixin使用方法看index.nuve
			 */
			//获取分类
			loadTabbars(){
				var _this = this
				
				this.$api.getType().then((res)=>{
				
		
				 var  tabList =	res.data.Data[_this.curTab]
					 
				 
				   tabList.forEach(item=>{
				   	item.newsList = [];
				   	item.loadMoreStatus = 0;  //加载更多 0加载前，1加载中，2没有更多了
				   	item.refreshing = 0;
				   	item.page = -1
				   })
				   _this.tabBars = tabList;
				   _this.loadNewsList('add');
				   
				})
			},
			//新闻列表
			loadNewsList(type){
				let tabItem = this.tabBars[this.tabCurrentIndex];
				
				//type add 加载更多 refresh下拉刷新
				if(type === 'add'){
					if(tabItem.loadMoreStatus === 2){
						return;
					}
					tabItem.loadMoreStatus = 1;
					tabItem.page = tabItem.page + 1
				}
				// #ifdef APP-PLUS
				else if(type === 'refresh'){
					tabItem.refreshing = true;
				}
				// #endif
				
				
				
				for(var i =0;i<this.tabBars.length;i++){
									  
									  if(i!=this.tabCurrentIndex && i!=this.tabCurrentIndex-1 && i!=this.tabCurrentIndex+1){
										  //只保留左右侧缓存
										  
										  let itemCache = this.tabBars[i]
										  itemCache.newsList = [];
										  itemCache.loadMoreStatus = 0;  //加载更多 0加载前，1加载中，2没有更多了
										  itemCache.refreshing = 0;
										  itemCache.page = -1
										  itemCache.loaded = false
									  }
				}
				
					let list = null;
										this.$api.getInfo(tabItem.id,tabItem.page).then((res)=>{
										
											res.data.Data.data.forEach(item=>{
												item.id = parseInt(Math.random() * 10000);
												tabItem.newsList.push(item);
											})
										})
				
					if(type === 'refresh'){
						tabItem.newsList = []; //刷新前清空数组
					}
					// list.forEach(item=>{
						
					// 	tabItem.newsList.push(item);
					// })
					//下拉刷新 关闭刷新动画
					if(type === 'refresh'){
						this.$refs.mixPulldownRefresh && this.$refs.mixPulldownRefresh.endPulldownRefresh();
						// #ifdef APP-PLUS
						tabItem.refreshing = false;
						// #endif
						tabItem.loadMoreStatus = 0;
					}
					//上滑加载 处理状态
					// if(type === 'add'){
					// 	tabItem.loadMoreStatus = tabItem.newsList.length > 40 ? 2: 0;
					// }
				
			},
			//新闻详情
			navToDetails(item){
				console.log(item.Url)
				window.open(item.Url,'_blank');  
			},
			
			//下拉刷新
			onPulldownReresh(){
				this.loadNewsList('refresh');
			},
			//上滑加载
			loadMore(){
				this.loadNewsList('add');
			},
			//设置scroll-view是否允许滚动，在小程序里下拉刷新时避免列表可以滑动
			setEnableScroll(enable){
				if(this.enableScroll !== enable){
					this.enableScroll = enable;
				}
			},
			tapType(item){
				this.curTab=item
				this.tabCurrentIndex=0,
				this.loadTabbars()
				this.modalName=null
			},

			//tab切换
			async changeTab(e){
				
				if(scrollTimer){
					//多次切换只执行最后一次
					clearTimeout(scrollTimer);
					scrollTimer = false;
				}
				let index = e;
				//e=number为点击切换，e=object为swiper滑动切换
				if(typeof e === 'object'){
					index = e.detail.current
				}
				if(typeof tabBar !== 'object'){
					tabBar = await this.getElSize("nav-bar")
				}
				//计算宽度相关
				let tabBarScrollLeft = tabBar.scrollLeft;
				let width = 0; 
				let nowWidth = 0;
				//获取可滑动总宽度
				for (let i = 0; i <= index; i++) {
					let result = await this.getElSize('tab' + i);
					width += result.width;
					if(i === index){
						nowWidth = result.width;
					}
				}
				if(typeof e === 'number'){
					//点击切换时先切换再滚动tabbar，避免同时切换视觉错位
					this.tabCurrentIndex = index; 
				}
				//延迟300ms,等待swiper动画结束再修改tabbar
				scrollTimer = setTimeout(()=>{
					if (width - nowWidth/2 > windowWidth / 2) {
						//如果当前项越过中心点，将其放在屏幕中心
						this.scrollLeft = width - nowWidth/2 - windowWidth / 2;
					}else{
						this.scrollLeft = 0;
					}
					if(typeof e === 'object'){
						this.tabCurrentIndex = index; 
					}
					this.tabCurrentIndex = index; 
					
					
					//第一次切换tab，动画结束后需要加载数据
					let tabItem = this.tabBars[this.tabCurrentIndex];
					if( tabItem.loaded !== true){
						this.loadNewsList('add');
						tabItem.loaded = true;
					}
				}, 300)
				
			},
			//获得元素的size
			getElSize(id) { 
				return new Promise((res, rej) => {
					let el = uni.createSelectorQuery().select('#' + id);
					el.fields({
						size: true,
						scrollOffset: true,
						rect: true
					}, (data) => {
						res(data);
					}).exec();
				});
			},
			search(e){
				uni.navigateTo({
					url: `/pages/details/details?data=${this.content}`
				})
			},tapRss(){
			 uni.navigateTo({
			 	url:'../rssHub/rssHub'
			 })
			}
		}
	}
</script>

<style lang='scss'>
	
	page, .content{
		
		height: 100%;
		
	}

	/* 顶部tabbar */
	.nav-bar{
	
		position: relative;
		z-index: 10;
		height: 90upx;
		white-space: nowrap;
		box-shadow: 0 2upx 8upx rgba(0,0,0,.06);
		background-color: #fff;
		.nav-item{
			text-overflow: ellipsis;
		    overflow:hidden; 
			display: inline-block;
			width: 150upx;
			height: 90upx;
			text-align: center;
			line-height: 90upx;
			font-size: 30upx;
			color: #303133;
			position: relative;
			&:after{
				content: '';
				width: 0;
				height: 0;
				border-bottom: 4upx solid #007aff;
				position: absolute;
				left: 50%;
				bottom: 0;
				transform: translateX(-50%);
				transition: .3s;
			}
		}
		.current{
			color: #007aff;
			&:after{
				width: 50%;
			}
		}
	}
	
	.swiper-box{
		height: 100%;
	}
	
	.panel-scroll-box{
		height: 100%;
		
		.panel-item{
			background: #fff;
			padding: 30px 0;
			border-bottom: 2px solid #000;
		}
	}
	.DrawerPage {
		position: fixed;
		width: 100vw;
		height: 100vh;
		left: 0vw;
		background-color: #f1f1f1;
		transition: all 0.4s;
	}
	
	.DrawerPage.show {
		transform: scale(0.9, 0.9);
		left: 85vw;
		box-shadow: 0 0 60upx rgba(0, 0, 0, 0.2);
		transform-origin: 0;
	}
	
	.DrawerWindow {
		position: absolute;
		width: 85vw;
		height: 100vh;
		left: 0;
		top: 0;
		transform: scale(0.9, 0.9) translateX(-100%);
		opacity: 0;
		pointer-events: none;
		transition: all 0.4s;
		padding: 100upx 0;
	}
	
	.DrawerWindow.show {
		transform: scale(1, 1) translateX(0%);
		opacity: 1;
		pointer-events: all;
	}
	
	.DrawerClose {
		position: absolute;
		width: 40vw;
		height: 100vh;
		right: 0;
		top: 0;
		color: transparent;
		padding-bottom: 30upx;
		display: flex;
		align-items: flex-end;
		justify-content: center;
		background-image: linear-gradient(90deg, rgba(0, 0, 0, 0.01), rgba(0, 0, 0, 0.6));
		letter-spacing: 5px;
		font-size: 50upx;
		opacity: 0;
		pointer-events: none;
		transition: all 0.4s;
	}
	
	.DrawerClose.show {
		opacity: 1;
		pointer-events: all;
		width: 15vw;
		color: #fff;
	}
	
	.DrawerPage .cu-bar.tabbar .action button.cuIcon {
		width: 64upx;
		height: 64upx;
		line-height: 64upx;
		margin: 0;
		display: inline-block;
	}
	
	.DrawerPage .cu-bar.tabbar .action .cu-avatar {
		margin: 0;
	}
	
	.DrawerPage .nav {
		flex: 1;
	}
	
	.DrawerPage .nav .cu-item.cur {
		border-bottom: 0;
		position: relative;
	}
	
	.DrawerPage .nav .cu-item.cur::after {
		content: "";
		width: 10upx;
		height: 10upx;
		background-color: currentColor;
		position: absolute;
		bottom: 10upx;
		border-radius: 10upx;
		left: 0;
		right: 0;
		margin: auto;
	}
	
	.DrawerPage .cu-bar.tabbar .action {
		flex: initial;
	}
</style>
